var csv = require('csv');
var request = require('request');
var async = require('async');

if (process.argv.length < 4) {
  console.log('Usage: node ' + process.argv[1] + '<Table Name> <File Name>');
  process.exit(1);
}

var fs = require('fs')
  , filename = process.argv[3]
  , tableName = process.argv[2]
  , url = "http://ust-nutrition.hopto.org:4984/" + tableName + "/";
fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err;
  csv().from.string(data).to.array(function(csvData) {
   var keys = csvData[0];
   var objs = {};
   for(var i = 1; i < csvData.length; i++) {
    var obj = {channels:["public"]};
    var data = csvData[i];
if(data.length == 0 || data.length == 1 && data[0].length == 0) continue;
    for(var j = 0; j < data.length; j++)
     if(keys[j] == "id")
      objs[data[j]] = obj;
     else
      obj[keys[j]] = data[j];
   }

   async.eachSeries(Object.keys(objs), function(key, callback) {
    console.log("Committing " + key + "...");
    request.get({url: url + key}, function(err, req, body) {
     if(err) console.log(err);
     else console.log(body);

body = JSON.parse(body);
if(!body.error)
objs[key]._rev = body._rev;
    request.put({url: url + key, json: objs[key]}, function(err, req, body) {
     if(err) console.log(err);
     else console.log(body);
     callback();
    });
    });
   });
  });
});

